<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="refForm" @submit="bindMobile">
      <van-field
        name="mobile"
        v-model="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
      ></van-field>
      <van-field name="code" v-model="code" placeholder="请输入验证码">
        <template #button>
          <!-- 动态class {类名：布尔值} -->
          <span
            @click="sendCode"
            class="btn-send"
            :class="{ active: time > 0 }"
            >{{ time > 0 ? `${time}s后重新发送` : '发送短信验证码' }}</span
          >
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { loginByQQAPI, bindMobileAPI } from '@/services'
import { useCodeByMobile } from '@/composables'
// 引入手机号和密码的校验规则
import { mobileRules } from '@/utils/rules'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const store = useUserStore()
const router = useRouter()

const isNeedBind = ref(false) //是否需要绑定手机号，默认为false
let openId = ''
const mobile = ref() //手机号
const code = ref() //验证码

const { sendCode, time, refForm } = useCodeByMobile(mobile, 'bindMobile')

onMounted(() => {
  /*global QC*/ //global是一个全局变量，不要校验
  // check用来判断 QQ是否登陆成功
  // getMe 用来获取openId
  if (QC.Login.check()) {
    QC.Login.getMe((id) => {
      openId = id
      loginByQQAPI(id, 'qq')
        .then((res) => {
          // console.log(res, 'res')
          loginSuccess(res.data)
        })
        .catch((err) => {
          // 没有绑定手机号
          console.log(err)
          isNeedBind.value = true
        })
    })
  }
})

// 登陆成功后操作
const loginSuccess = (user: User) => {
  // 1.存储用户信息
  store.setUser(user)
  // 2.跳转页面
  router.push(store.returnUrl || '/home')
  // 回调地址使用之后把本地存的上次回调地址清空
  store.setReturnUrl('')
}

// 绑定手机号
const bindMobile = async () => {
  const res = await bindMobileAPI(mobile.value, code.value, openId)
  // console.log(res)
  loginSuccess(res.data)
}
</script>
